package com.itheima.controller;

import com.alibaba.druid.util.Utils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.GetThreadLocal;
import com.itheima.common.R;
import com.itheima.pojo.*;
import com.itheima.service.*;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/11/7 11:48
 */
@RestController
@RequestMapping("/order")
public class OrdersController {
    
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 历史订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R getUserPage(int page, int pageSize){
        IPage<Orders> iPage = new Page<>(page, pageSize);
        IPage<Orders> page1 = ordersService.page(iPage);
        return R.success(page1);
    }

    /**
     * 购物车结算
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        // 雪花算法生成订单号
        Long orderNumber = IdWorker.getId();
        Long userId = GetThreadLocal.getThreadLocal();

        // 查询购物车，计算总金额，和添加到订单想情
        LambdaQueryWrapper<ShoppingCart> querryWrapper = new LambdaQueryWrapper<>();
        querryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(querryWrapper);
        // 调用计算总金额方法
        BigDecimal amount = getAmounts(shoppingCartList);

        // 查询User表获取电话号码
        LambdaQueryWrapper<User> querryWrapperUser = new LambdaQueryWrapper<>();
        querryWrapperUser.eq(User::getId, userId);
        User user = userService.getOne(querryWrapperUser);
        
        // 查询地址表，获取地址
        LambdaQueryWrapper<AddressBook> querryWrapperAddrss = new LambdaQueryWrapper<>();
        querryWrapperAddrss.eq(AddressBook::getUserId, userId);
        querryWrapperAddrss.eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = addressBookService.getOne(querryWrapperAddrss);
        
        // 封装Orders数据
        orders.setNumber(String.valueOf(orderNumber));
        orders.setStatus(1);
        orders.setUserId(userId);
        orders.setUserName("二锤子用户:"+user.getPhone());
        orders.setOrderTime(LocalDateTime.now());
        orders.setAmount(amount);
        orders.setPhone(user.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        // 添加到订单表
        ordersService.save(orders);

        // 添加到订单详情表
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orderNumber);
            orderDetailService.save(orderDetail);
        }
        // 清空购物车
        shoppingCartService.remove(querryWrapper);
        return R.success("添加成功！");
    }

    /**
     * 计算购物车的总金额
     * @param shoppingCartList
     * @return
     */
    private BigDecimal getAmounts(List<ShoppingCart> shoppingCartList) {

        BigDecimal bigDecimal = new BigDecimal(0);
        for (ShoppingCart shoppingCart : shoppingCartList) {
            Integer number = shoppingCart.getNumber();
            BigDecimal amount = shoppingCart.getAmount();
            
            BigDecimal multiply = amount.multiply(new BigDecimal(number));
            // 总金额
            bigDecimal = bigDecimal.add(multiply);
        }
        return bigDecimal;
    }

    /**
     * 后台订单明细
     * @return
     */
    @GetMapping("/page")
    public R orderDetailPage(int page, int pageSize, String number, DateTimeLiteralExpression.DateTime beginTime, DateTimeLiteralExpression.DateTime endTime){
        IPage<Orders> iPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> querrywrapper = new LambdaQueryWrapper<>();
        querrywrapper.eq(number != null, Orders::getNumber, number);
        // 下单时间区间
        querrywrapper.gt(beginTime != null, Orders::getOrderTime, beginTime).
        lt(beginTime != null, Orders::getOrderTime, endTime);
        IPage<Orders> pageResult = ordersService.page(iPage, querrywrapper);
        return R.success(pageResult);
    }
}
